package com.carrentalplatform.controller;

import com.carrentalplatform.model.User;
import com.carrentalplatform.service.UserService;
import com.carrentalplatform.vo.Result;
import com.carrentalplatform.vo.UserLoginVO;
import com.carrentalplatform.vo.UserRegisterVO;
import com.carrentalplatform.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<UserVO> login(@RequestBody UserLoginVO loginVO) {
        User user = userService.login(loginVO.getUsername(), loginVO.getPassword());
        if (user == null) {
            return Result.fail("用户名或密码错误");
        }
        
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        // 不返回密码
        userVO.setPassword(null);
        
        return Result.success(userVO);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<Void> register(@RequestBody UserRegisterVO registerVO) {
        User user = new User();
        BeanUtils.copyProperties(registerVO, user);
        
        boolean success = userService.register(user);
        if (!success) {
            return Result.fail("注册失败，用户名已存在");
        }
        
        return Result.success();
    }

    /**
     * 用户实名认证
     */
    @PostMapping("/verify")
    public Result<Void> verifyIdentity(@RequestParam Long userId, 
                                      @RequestParam String realName, 
                                      @RequestParam String idCard) {
        boolean success = userService.verifyIdentity(userId, realName, idCard);
        if (!success) {
            return Result.fail("实名认证失败");
        }
        
        return Result.success();
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/{id}")
    public Result<UserVO> getUserInfo(@PathVariable Long id) {
        User user = userService.getById(id);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        // 不返回密码
        userVO.setPassword(null);
        
        return Result.success(userVO);
    }
} 